package com.copc.common.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

/**
 * 请求校验工具类
 * 
 * @author 捷微团队
 * @date 2013-05-18
 */
@Slf4j
public class SignUtil {
	
	/**
	 * 生成签名 added by guo 20150722
	 * 算法如下：
	 * 1. 将token、timestamp、加密后的报文内容进行字典序排序。
	 * 2. 将三个值拼成一个字符串进行sha1加密。
	 * 3. 服务端会将加密后的字符串与signature进行比较，标识该请求是来自于clientcode。
	 * @param token
	 * @param timestamp
	 * @param nonce
	 * @return
	 */
	public static String generateSignature(String token,String timestamp,String nonce){
		
		log.info(String.format("token===>%s, timestamp===>%s, nonce===>%s", token,timestamp,nonce));
		
		String[] arr = new String[] { token, timestamp, nonce };
		// 将token、timestamp、nonce三个参数进行字典序排序
		Arrays.sort(arr);
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);
		}
		MessageDigest md = null;
		String tmpStr = null;

		try {
			md = MessageDigest.getInstance("SHA-1");
			// 将三个参数字符串拼接成一个字符串进行sha1加密
			byte[] digest = md.digest(content.toString().getBytes("UTF-8"));
			tmpStr = byteToStr(digest);
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
			log.error("generateSignature digest failed",e);
		}

		content = null;
		return tmpStr;
	}

	public static String generateTokenSignature(String appId,String timestamp,String appSecret){

		log.info(String.format("token===>%s, timestamp===>%s, nonce===>%s", appId,timestamp,appSecret));

		String[] arr = new String[] { appId, timestamp, appSecret };
		// 将token、timestamp、nonce三个参数进行字典序排序
		Arrays.sort(arr);
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);
		}
		MessageDigest md = null;
		String tmpStr = null;

		try {
			md = MessageDigest.getInstance("SHA-1");
			// 将三个参数字符串拼接成一个字符串进行sha1加密
			byte[] digest = md.digest(content.toString().getBytes("UTF-8"));
			tmpStr = byteToStr(digest);
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
			log.error("generateSignature digest failed",e);
		}

		content = null;
		return tmpStr;
	}

	/**
	 * 验证签名
	 *
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @return
	 */
	public static boolean checkTokenSignature(String appId,String signature, String timestamp, String appSecret) {

		String tmpStr = generateSignature(appId,timestamp,appSecret);

		// 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
		if(StringUtils.isEmpty(tmpStr) || StringUtils.isEmpty(signature)){
			return false;
		}
		return tmpStr.equals(signature.toUpperCase());
	}
	
	// 与接口配置信息中的Token要一致
	/**
	 * 验证签名
	 * 
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @return
	 */
	public static boolean checkSignature(String token,String signature, String timestamp, String nonce) {
		
		String tmpStr = generateSignature(token,timestamp,nonce);

		// 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
		if(StringUtils.isEmpty(tmpStr) || StringUtils.isEmpty(signature)){
			return false;
		}
		return tmpStr.equals(signature.toUpperCase());
	}

	/**
	 * 将字节数组转换为十六进制字符串
	 * 
	 * @param byteArray
	 * @return
	 */
	public static String byteToStr(byte[] byteArray) {
		String strDigest = "";
		for (int i = 0; i < byteArray.length; i++) {
			strDigest += byteToHexStr(byteArray[i]);
		}
		return strDigest;
	}

	/**
	 * 将字节转换为十六进制字符串
	 * 
	 * @param mByte
	 * @return
	 */
	private static String byteToHexStr(byte mByte) {
		
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		char[] tempArr = new char[2];
		tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
		tempArr[1] = Digit[mByte & 0X0F];

		String s = new String(tempArr);
		return s;
	}
}
